package presentation;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import businessObject.GestionUsuario;

import dataTransferObject.Usuario;

/**
 * Servlet implementation class FrontController
 */
public class FrontController extends HttpServlet {
		private static final long serialVersionUID = 1L;

		public void init() throws ServletException {
		}

		protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			processRequest(request, response);
		}

		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			processRequest(request, response);
		}
		
		protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			int idRol = logado(request);
			
			if (idRol == 0) {
				response.sendRedirect("index.jsp?usuario=no");
			} else {
				String resource = null;
				if (idRol == 1) {
					resource = request.getParameter("resource");
				} else {
					resource = "lugaresValidar.jsp";
				}
				RequestDispatcher dispatcher = request.getRequestDispatcher(resource);
				if (dispatcher != null) {
					dispatcher.forward(request, response);
				}
			}
		}
		
		public int logado(HttpServletRequest request) {
			int res = 0;
			
			HttpSession session = request.getSession(false);
			
			String userForm = request.getParameter("user");
			String passForm = request.getParameter("pass");
			String rolForm = request.getParameter("rol");
			
			if (session == null ) {		// Estamos en el inicio (login)
				session = request.getSession();
				
				if (userForm == null || passForm == null || rolForm == null ||
						userForm.length() == 0 || passForm.length() == 0) {
					res = 0;
				} else {
					int idRol = Integer.parseInt(rolForm);
					res = valido(session, userForm, passForm, idRol);
				}
			} else {
				if (userForm == null || passForm == null || rolForm == null) {
					res = 1;	// Solo se usa el rol Administrador en en login del usuario
				} else {
					int idRol = Integer.parseInt(rolForm);
					res = valido(session, userForm, passForm, idRol);	
				}
			}
			return res;
		}

		public int valido(HttpSession session, String userForm, String passForm, int idRol) {
			int res = 0;
			int idExists = GestionUsuario.getInstance().validarUsuario(userForm, passForm, idRol);
			
			if (idExists >= 0) {
				int idUsuario = idExists;
				session.setAttribute("session.idusuario", idUsuario);
				session.setAttribute("session.user", userForm);
				res = idRol;
			}
			return res;
		}
}
